// pages/my/address/add/add.js
var app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var address = {};
    var hasAddress;
    if (options.address) {
      wx.setNavigationBarTitle({
        title: '编辑收货地址',
      });
      address = JSON.parse(options.address);
      hasAddress = true;
    }
    else {
      wx.setNavigationBarTitle({
        title: '添加收货地址',
      });
      address = {
        name: '',
        card: '',
        phone: '',
        province: '',
        address: '',
        addressName: '',
        city: '',
        cityName:'',
        district:'',
        districtName:'',
        isdefault: '0'
      }
      hasAddress = false;
    }
    this.setData({
      address: address,
      hasAddress: hasAddress
    });
    this.loadRegion();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    return app.shareToIndex();
  },
  checkboxChange: function (event) {
    var checkvals = event.detail.value;
    var address = this.data.address;
    if (checkvals.length > 0) {
      address.isdefault = '1';
    }
    else {
      address.isdefault = '0';
    }
    this.setData({
      address: address
    });
  },
  dealAddress: function (event) {
    if (this.data.address.name == '' || this.data.address.phone == '' || this.data.address.address == '') {
      wx.showToast({
        icon: 'none',
        title: '地址信息不完整',
      });
      return;
    }
    if (this.data.address.province == '' || this.data.address.province == 0){
      wx.showToast({
        icon: 'none',
        title: '地址信息不完整',
      });
      return;
    }
    if (this.data.citySets.length > 0 && (this.data.address.city == '' || this.data.address.city == 0)){
      wx.showToast({
        icon: 'none',
        title: '地址信息不完整',
      });
      return;
    }
    var url = '';
    var dealtype = event.currentTarget.dataset.dealtype;
    var params = {
      consignee: this.data.address.name,
      mobile: this.data.address.phone,
      province: this.data.address.province,
      city: this.data.address.city,
      district: this.data.address.district,
      idCard: this.data.address.card,
      address: this.data.address.address,
      is_default: this.data.address.isdefault
    };
    if (dealtype == 'add') {
      url = '/index.php/api/User/add_address';
    }
    else if (dealtype == 'edit') {
      params.id = this.data.address.addressid;
      url = '/index.php/api/User/edit_address';
    }
    else if (dealtype == 'delete') {
      params = {
        id: this.data.address.addressid
      }
      url = '/index.php/api/User/del_address';
    }
    app.request(url, params).then(this.dealAddressCallBack.bind(this))
  },
  dealAddressCallBack: function (res) {
    wx.hideToast();
    var icon = 'success'
    if (res.status != 'ok') {
      icon = 'none';
    }
    else {
      var delayid = setTimeout(function () {
        clearTimeout(delayid);
        wx.navigateBack({});
      }, 1000);
    }
    wx.showToast({
      icon: icon,
      title: res.msg,
      duration: 1000
    });

  },
  checkInput: function (event) {
    var inputtype = event.currentTarget.dataset.inputtype;
    var inputval = event.detail.value;
    var address = this.data.address;
    if (inputtype == 'name') {
      address.name = inputval;
    }
    else if (inputtype == 'card') {
      address.card = inputval;
    }
    else if (inputtype == 'phone') {
      address.phone = inputval;
    }
    else if (inputtype == 'address') {
      address.address = inputval;
    }
    this.setData({
      address: address
    });
  },
  loadRegion: function () {
    var url = '/api/Cart/regionlist';
    app.request(url).then(this.loadRegionCallBack.bind(this))
  },
  loadRegionCallBack: function (res) {
    var address = this.data.address;
    var allprovince = res.result;
    var provinceArr = [];
    for (var i = 0; i < allprovince.length; i++) {
      provinceArr.push(allprovince[i].name);
      if (address.province == allprovince[i].id) {
        address.provinceName = allprovince[i].name;
      }
    }
    this.setData({
      allprovince: allprovince,
      provinceSets: provinceArr,
      address: address
    });
    if(address.province!=''){
      this.loadArea(address.province);
    }
  },
  addressChange: function (e) {
    var ptype = e.currentTarget.dataset.picktype;
    if (ptype == 'province') {
      var province = e.detail.value;
      var address = this.data.address;
      address.provinceName = this.data.allprovince[province].name;
      address.province = this.data.allprovince[province].id;
      address.city = 0;
      address.cityName = '';
      address.district = 0;
      address.districtName = ''
      this.setData({
        address: address,
        proviceIndex: province,
        citySets:[],
        areaSets:[]
      });
      this.loadArea(address.province);
    }
    else if(ptype == 'city'){
      var city = e.detail.value;
      var address = this.data.address;
      var citySets = app.globalData.cityarea[this.data.address.province];
      address.cityName = citySets[city].name;
      address.city = citySets[city].id;
      address.district = 0;
      address.districtName = ''
      this.setData({
        address: address,
        cityIndex: city,
        areaSets: []
      });
      this.loadSubArea(address.city);
    }
    else if(ptype == 'area'){
      var area = e.detail.value;
      var address = this.data.address;
      var areaSets = app.globalData.areaSets[this.data.address.city];
      address.districtName = areaSets[area].name;
      address.district = areaSets[area].id;
      this.setData({
        address: address
      })
    }
  },
  loadArea:function(provinceId){
    if (app.globalData.cityarea) {
      if (app.globalData.cityarea[provinceId]) {
        var address = this.data.address;
        var cityArr = [];
        var citySets = app.globalData.cityarea[provinceId];
        if(citySets.length > 0){
          for (var i = 0; i < citySets.length; i++) {
            cityArr.push(citySets[i].name);
            if (address.city == citySets[i].id) {
              address.cityName = citySets[i].name;
            }
          }
          if(address.city == ''|| address.city == 0){
            address.city = citySets[0].id;
            address.cityName = citySets[0].name;
          }
          this.setData({
            address: address,
            citySets: cityArr
          });

          this.loadSubArea(address.city);
        }
        else{
          this.reqCityArea(provinceId);
        }
      }
      else{
        this.reqCityArea(provinceId);
      }
    }
    else{
      this.reqCityArea(provinceId);
    }
  },
  loadSubArea:function(cityId){
    if (app.globalData.areaSets){
      if(app.globalData.areaSets[cityId]){
        var address = this.data.address;
        var areaArr = [];
        var areaSets = app.globalData.areaSets[cityId];
        if (areaSets.length > 0) {
          for (var i = 0; i < areaSets.length; i++) {
            areaArr.push(areaSets[i].name);
            if (address.district == areaSets[i].id) {
              address.districtName = areaSets[i].name;
            }
          }
          if (address.district == '' || address.district == 0) {
            address.district = areaSets[0].id;
            address.districtName = areaSets[0].name;
          }
          this.setData({
            address: address,
            areaSets: areaArr
          });
        }
        else {
          this.reqSubArea(cityId);
        }
      }
      else{
        this.reqSubArea(cityId);
      }
    }
    else{
      this.reqSubArea(cityId);
    }
  },
  reqSubArea:function(cityId){
    app.showLoading();
    var url = '/index.php/api/Cart/getRegionByParentId';
    var params = {
      parent_id: cityId
    };
    app.request(url, params).then(this.reqSubAreaCallBack.bind(this))
  },
  reqSubAreaCallBack:function(res){
    app.hideLoading();
    if (res.status != 'ok') {
      return;
    }
    var address = this.data.address;
    if (res.result.length <= 0) {
      address.district = '';
      address.districtName = '';
      this.setData({
        address: address,
        areaSets: []
      });
      return;
    }
    var city = this.data.address.city;
    if (app.globalData.areaSets) {
      app.globalData.areaSets[city] = res.result;
    }
    else {
      app.globalData.areaSets = {};
      app.globalData.areaSets[city] = res.result;
    }
    var areaSets = [];
    var address = this.data.address;
    for (var i = 0; i < res.result.length; i++) {
      areaSets.push(res.result[i].name);
      if (address.district == res.result[i].id) {
        address.districtName = res.result[i].name;
      }
    }
    if (address.district == '' || address.district == 0) {
      address.district = res.result[0].id;
      address.districtName = res.result[0].name;
    }
    this.setData({
      areaSets: areaSets,
      address: address
    });
  },
  reqCityArea: function (provinceId){
    app.showLoading();
    var url = '/index.php/api/Cart/getRegionByParentId';
    var params = {
      parent_id: provinceId
    };
    app.request(url, params).then(this.reqCityAreaCallBack.bind(this))
  },
  reqCityAreaCallBack:function(res){
    app.hideLoading();
    if(res.status != 'ok'){
      return;
    }
    var address = this.data.address;
    if(res.result.length<=0){
      address.city = '';
      address.cityName = '';
      address.district = '';
      address.districtName = '';
      this.setData({
        address: address,
        citySets:[],
        areaSets:[]
      });
      return;
    }
    var provinceId = this.data.address.province;
    if (app.globalData.cityarea){
      app.globalData.cityarea[provinceId] = res.result;
    }
    else{
      app.globalData.cityarea = {};
      app.globalData.cityarea[provinceId] = res.result;
    }
    var citySets = [];
    var address = this.data.address;
    for (var i = 0; i < res.result.length; i++) {
      citySets.push(res.result[i].name);
      if (address.city == res.result[i].id){
        address.cityName = res.result[i].name;
      }
    }
    if (address.city == '' || address.city == 0) {
      address.city = res.result[0].id;
      address.cityName = res.result[0].name;
    }
    
    this.setData({
      citySets: citySets,
      address: address
    });
    this.loadSubArea(address.city);
  }
})